package main

import (
	"fmt"
	"golang.org/x/sync/errgroup"
	"net/http"
	"sync"
	"time"
)

func goroutineDemo1() {
	fmt.Println("Hello Goroutine！")
}

func worker(x int, wg *sync.WaitGroup) {
	defer wg.Done()
	for i := 0; i < 3; i++ {
		fmt.Printf("worker %d：%d\n", x, i)
	}
}

func a() {
	for i := 1; i < 10; i++ {
		fmt.Println("A:", i)
	}
}

func b() {
	for i := 1; i < 10; i++ {
		fmt.Println("B:", i)
	}
}

func RecoverGoroutinePanic() {

	go func() {
		defer func() {
			if err := recover(); err != nil {
				fmt.Println(fmt.Sprintf("recover panic:%v\n", err))
			}
		}()

		fmt.Println("in goroutine ...")
		panic("panic in goroutine")
	}()

	time.Sleep(time.Second)
}

func FetchUrlDemo() {
	waitGroup := sync.WaitGroup{}

	var urls = []string{
		"http://pkg.go.dev",
		"http://www.liwenzhou.com",
		"http://www.yixieqitawangzhi.com",
	}

	for _, url := range urls {
		waitGroup.Add(1)
		go func(urlstr string) {
			defer waitGroup.Done()
			resp, err := http.Get(urlstr)
			if err != nil {

				return
			}
			fmt.Printf("获取%s成功\n", urlstr)
			resp.Body.Close()
		}(url)
	}
	waitGroup.Wait()
}

/**
type Group struct {
	cancel func()

	wg sync.WaitGroup

	errOnce sync.Once
	err     error
}
*/

func FetchUrlDemo1() {
	var group = new(errgroup.Group)
	var urls = []string{
		"http://www.yixieqitawangzhi.com",
		"http://pkg.go.dev",
		"http://www.liwenzhou.com",
		"http://www.yixieqitawangzhiaaa.com",
		"http://pkg.go.dev",
		"http://www.liwenzhou.com",
	}

	for _, url := range urls {
		group.Go(func() error {
			resp, err := http.Get(url)
			if err == nil {
				fmt.Printf("获取%s成功\n", url)
				resp.Body.Close()
			}
			return err // 返回错误
		})
		err := group.Wait()
		if err != nil {
			fmt.Println(fmt.Sprintf("%v", err))
		}
	}
}
